/**
 * Test Configuration Factory
 * Creates test-friendly configurations for unit testing
 */

const ValidatorManager = require('../validators/validator-manager');

class TestConfigFactory {
  /**
   * Create minimal valid configuration
   * @returns {Object} Minimal configuration
   */
  static createMinimalConfig() {
    return {
      version: '1.0.0',
      current_provider_model: 'test-test-model',
      providers: {
        test: {
          base: 'https://api.test.com',
          api_key: 'test_api_key',
          models: [
            {
              id: 'test-test-model', // 修复ID匹配问题
              name: 'Test Model',
              type: 'vision',
              capabilities: ['image_analysis'],
              max_tokens: 4096,
              supports_vision: true,
              enabled: true
            }
          ]
        }
      }
    };
  }

  /**
   * Create full configuration with all sections
   * @returns {Object} Full configuration
   */
  static createFullConfig() {
    return {
      version: '1.0.0',
      current_provider_model: 'test-test-model',
      providers: {
        test: this.createTestProvider(),
        mock: this.createMockProvider()
      },
      http_server: {
        port: 3000,
        auto_start: false,
        host: 'localhost',
        cors: {
          enabled: true,
          origins: ['*']
        }
      },
      logging: {
        level: 'info',
        retention_days: 7,
        max_file_size: '10MB',
        file_enabled: false,
        console_enabled: true,
        timestamp_format: 'ISO',
        colors: true
      },
      mcp: {
        server_name: 'test-vision-analyzer',
        server_version: '1.0.0',
        timeout: 5000
      },
      features: {
        auto_model_selection: true,
        cache_analysis: false,
        debug_mode: true
      }
    };
  }

  /**
   * Create configuration with custom overrides
   * @param {Object} overrides - Configuration overrides
   * @returns {Object} Configuration with overrides
   */
  static createConfigWithOverrides(overrides = {}) {
    const baseConfig = this.createMinimalConfig();
    return this.mergeConfig(baseConfig, overrides);
  }

  /**
   * Create multiple providers configuration
   * @returns {Object} Multiple providers config
   */
  static createMultipleProvidersConfig() {
    return {
      version: '1.0.0',
      current_provider_model: 'test-test-model',
      providers: {
        test: this.createTestProvider(),
        mock: this.createMockProvider(),
        openai: this.createOpenAIProvider(),
        azure: this.createAzureProvider()
      }
    };
  }

  /**
   * Create configuration for testing error cases
   * @param {string} errorType - Type of error to create
   * @returns {Object} Invalid configuration
   */
  static createInvalidConfig(errorType = 'missing_required') {
    switch (errorType) {
      case 'missing_required':
        return {
          // Missing version
          current_provider_model: 'test-test-model'
          // Missing providers
        };

      case 'invalid_version':
        return {
          version: 'invalid-version',
          current_provider_model: 'test-test-model',
          providers: {
            test: this.createTestProvider()
          }
        };

      case 'no_providers':
        return {
          version: '1.0.0',
          current_provider_model: 'test-test-model',
          providers: {}
        };

      case 'invalid_provider':
        return {
          version: '1.0.0',
          current_provider_model: 'test-test-model',
          providers: {
            test: {
              base: 'invalid-url',
              api_key: 123, // should be string
              models: 'invalid' // should be array
            }
          }
        };

      case 'circular_dependency':
        return {
          version: '1.0.0',
          current_provider_model: 'non-existent-model',
          providers: {
            test: this.createTestProvider()
          }
        };

      default:
        return {};
    }
  }

  /**
   * Create test provider configuration
   * @returns {Object} Test provider config
   */
  static createTestProvider() {
    return {
      base: 'https://api.test.com',
      api_key: 'test_api_key',
      models: [
        {
          id: 'test-test-model', // 修复ID匹配问题
          name: 'Test Model',
          type: 'vision',
          capabilities: ['image_analysis', 'ui_analysis'],
          max_tokens: 4096,
          supports_vision: true,
          enabled: true,
          cost_per_token: 0.01
        },
        {
          id: 'test-model-v2',
          name: 'Test Model v2',
          type: 'vision',
          capabilities: ['image_analysis', 'design_tokens'],
          max_tokens: 8192,
          supports_vision: true,
          enabled: true,
          cost_per_token: 0.02
        }
      ],
      timeout: 30000,
      max_retries: 3,
      rate_limit: {
        requests_per_minute: 60,
        requests_per_hour: 3600
      }
    };
  }

  /**
   * Create mock provider configuration
   * @returns {Object} Mock provider config
   */
  static createMockProvider() {
    return {
      base: 'https://api.mock.com',
      api_key: 'mock_api_key',
      models: [
        {
          id: 'mock-model',
          name: 'Mock Model',
          type: 'vision',
          capabilities: ['image_analysis'],
          max_tokens: 2048,
          supports_vision: true,
          enabled: true
        }
      ]
    };
  }

  /**
   * Create OpenAI provider configuration
   * @returns {Object} OpenAI provider config
   */
  static createOpenAIProvider() {
    return {
      base: 'https://api.openai.com/v1',
      api_key: 'sk-test-key',
      models: [
        {
          id: 'gpt-4-vision-preview',
          name: 'GPT-4 Vision Preview',
          type: 'vision',
          capabilities: ['image_analysis', 'text_generation'],
          max_tokens: 4096,
          supports_vision: true,
          enabled: true,
          cost_per_token: 0.03
        }
      ]
    };
  }

  /**
   * Create Azure provider configuration
   * @returns {Object} Azure provider config
   */
  static createAzureProvider() {
    return {
      base: 'https://api.openai.azure.com',
      api_key: 'azure-test-key',
      models: [
        {
          id: 'gpt-4-vision-preview',
          name: 'GPT-4 Vision Preview',
          type: 'vision',
          capabilities: ['image_analysis'],
          max_tokens: 4096,
          supports_vision: true,
          enabled: true
        }
      ]
    };
  }

  /**
   * Deep merge configuration objects
   * @param {Object} target - Target configuration
   * @param {Object} source - Source configuration to merge
   * @returns {Object} Merged configuration
   */
  static mergeConfig(target, source) {
    const result = { ...target };

    for (const [key, value] of Object.entries(source)) {
      if (value === null || value === undefined) {
        continue;
      }

      if (typeof value === 'object' && !Array.isArray(value) && value !== null) {
        result[key] = this.mergeConfig(result[key] || {}, value);
      } else {
        result[key] = value;
      }
    }

    return result;
  }

  /**
   * Validate test configuration
   * @param {Object} config - Configuration to validate
   * @param {Object} options - Validation options
   * @returns {Object} Validation result
   */
  static validateTestConfig(config, options = {}) {
    const manager = ValidatorManager.getInstance();
    return manager.validateForTest(config, options);
  }

  /**
   * Create and validate test configuration
   * @param {Object} overrides - Configuration overrides
   * @param {Object} options - Validation options
   * @returns {Object} Validation result
   */
  static createAndValidateTestConfig(overrides = {}, options = {}) {
    const config = this.createConfigWithOverrides(overrides);
    return this.validateTestConfig(config, options);
  }

  /**
   * Create single provider configuration with specific model
   * @param {string} providerName - Provider name
   * @param {string} modelId - Model ID
   * @returns {Object} Single provider configuration
   */
  static createSingleProviderConfig(providerName = 'test', modelId = 'test-model') {
    return {
      version: '1.0.0',
      current_provider_model: modelId,
      providers: {
        [providerName]: {
          base: `https://api.${providerName}.com`,
          api_key: `${providerName}_api_key`,
          models: [
            {
              id: modelId,
              name: `${providerName.charAt(0).toUpperCase() + providerName.slice(1)} Model`,
              type: 'vision',
              capabilities: ['image_analysis'],
              max_tokens: 4096,
              supports_vision: true,
              enabled: true
            }
          ]
        }
      }
    };
  }

  /**
   * Create configuration with different provider types
   * @returns {Object} Multi-type provider configuration
   */
  static createMultiTypeProviderConfig() {
    return {
      version: '1.0.0',
      current_provider_model: 'openai-gpt-4-vision',
      providers: {
        openai: {
          base: 'https://api.openai.com/v1',
          api_key: 'sk-openai-key',
          models: [
            {
              id: 'openai-gpt-4-vision',
              name: 'GPT-4 Vision',
              type: 'vision',
              capabilities: ['image_analysis', 'text_generation'],
              max_tokens: 4096,
              supports_vision: true,
              enabled: true
            }
          ]
        },
        anthropic: {
          base: 'https://api.anthropic.com',
          api_key: 'sk-ant-key',
          models: [
            {
              id: 'anthropic-claude-3-vision',
              name: 'Claude 3 Vision',
              type: 'vision',
              capabilities: ['image_analysis', 'ui_analysis'],
              max_tokens: 8192,
              supports_vision: true,
              enabled: true
            }
          ]
        }
      }
    };
  }

  /**
   * Create configuration with disabled models
   * @returns {Object} Configuration with disabled models
   */
  static createConfigWithDisabledModels() {
    return {
      version: '1.0.0',
      current_provider_model: 'test-test-model',
      providers: {
        test: {
          base: 'https://api.test.com',
          api_key: 'test_api_key',
          models: [
            {
              id: 'test-test-model',
              name: 'Test Model',
              type: 'vision',
              capabilities: ['image_analysis'],
              max_tokens: 4096,
              supports_vision: true,
              enabled: true
            },
            {
              id: 'test-disabled-model',
              name: 'Disabled Model',
              type: 'vision',
              capabilities: ['image_analysis'],
              max_tokens: 4096,
              supports_vision: true,
              enabled: false
            }
          ]
        }
      }
    };
  }

  /**
   * Create edge case configuration for testing
   * @param {string} edgeType - Type of edge case
   * @returns {Object} Edge case configuration
   */
  static createEdgeCaseConfig(edgeType = 'minimal') {
    switch (edgeType) {
      case 'minimal':
        return {
          version: '1.0.0',
          current_provider_model: 'test-model',
          providers: {
            test: {
              base: 'https://api.test.com',
              api_key: 'key',
              models: [
                {
                  id: 'test-model',
                  name: 'Model',
                  type: 'vision',
                  capabilities: [],
                  max_tokens: 1,
                  supports_vision: true,
                  enabled: true
                }
              ]
            }
          }
        };

      case 'empty_capabilities':
        return this.createConfigWithOverrides({
          providers: {
            test: {
              models: [
                {
                  id: 'test-test-model',
                  name: 'Test Model',
                  type: 'vision',
                  capabilities: [], // Empty capabilities
                  max_tokens: 4096,
                  supports_vision: true,
                  enabled: true
                }
              ]
            }
          }
        });

      case 'single_capability':
        return this.createConfigWithOverrides({
          providers: {
            test: {
              models: [
                {
                  id: 'test-test-model',
                  name: 'Test Model',
                  type: 'vision',
                  capabilities: ['single_capability'], // Single capability
                  max_tokens: 4096,
                  supports_vision: true,
                  enabled: true
                }
              ]
            }
          }
        });

      default:
        return this.createMinimalConfig();
    }
  }

  /**
   * Get configuration scenarios for testing
   * @returns {Object} Test scenarios
   */
  static getTestScenarios() {
    return {
      minimal: () => this.createMinimalConfig(),
      full: () => this.createFullConfig(),
      multipleProviders: () => this.createMultipleProvidersConfig(),
      singleProvider: (providerName, modelId) => this.createSingleProviderConfig(providerName, modelId),
      multiType: () => this.createMultiTypeProviderConfig(),
      withDisabledModels: () => this.createConfigWithDisabledModels(),
      edgeCase: (edgeType) => this.createEdgeCaseConfig(edgeType),
      customOverrides: (overrides) => this.createConfigWithOverrides(overrides),
      invalid: (errorType) => this.createInvalidConfig(errorType)
    };
  }
}

module.exports = TestConfigFactory;